﻿using Api.Common;

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using PetaPoco;
using AppManager.Model;

namespace PushTask
{
    public class SignalrPush
    {
        public static void Send()
        {
            LogHelper.WriteCreateNewLog(LogType.signalrInfo, "开始执行");

            Database db = new Database();


            List<Message> needSendList = Push.GetNeedSendMessageList(db);

            if (needSendList.Count() == 0)
            {
                LogHelper.WriteCreateNewLog(LogType.signalrInfo, "没有需要发送的消息list.Count==0");
                return;
            }

            List<MessageDevice> successList = new List<MessageDevice>();
            List<MessageDevice> errorList = new List<MessageDevice>();

            foreach (var m in needSendList)
            {
                var messageId = m.Id;
                int devicetype = 0;
                bool isUseGoogle = false;
                var mv = MessageDeviceBLL.GetFirstDevice(messageId, devicetype, isUseGoogle);


                if (mv != null)
                {
                    var count = MessageDeviceBLL.GetDeviceCount(messageId, devicetype, isUseGoogle);
                    //Console.WriteLine("stratId:{0}  count:{1}", mv.Id, count);

                    List<DeviceData> devices = new List<DeviceData>();
                    int currentCount = 0;
                    int size = 10000;
                    int id = mv.Id;

                    //每隔一千條獲取一次數據
                    do
                    {
                        devices = MessageDeviceBLL.GetDevices(id, messageId, devicetype, isUseGoogle, size);

                        currentCount += size;
                        id += size;

                        SignalrSend(m, devices);

                    } while (currentCount <= count);
                }
            }

            LogHelper.WriteCreateNewLog(LogType.signalrInfo, "结束执行");
        }

        //一個重要的問題是怎麼解決連接之後的console
        private static void SignalrSend(Message message, IEnumerable<DeviceData> devicedatas)
        {
            Database db = new Database();
            List<int> successList = new List<int>();
            List<int> errorList = new List<int>();
            successList.Add(-1);
            errorList.Add(-1);
            try
            {
                devicedatas = from a in devicedatas where !string.IsNullOrEmpty(a.DeviceStr) select a;
                var list = devicedatas.Select(s => s.DeviceStr).ToArray();

                var obj = JsonConvert.DeserializeObject(message.Data);
                var str = new SignalrData
                {
                    content = message.Content,
                    data = obj,
                    mid = message.Id
                }.ToString();
                //調取服務器發送推送消息                        
                new SendSignalrMessage().Send(str, list);
                successList.AddRange(devicedatas.Select(s => s.Id));
            }
            catch (Exception ex)
            {
                errorList.AddRange(devicedatas.Select(s => s.Id));
                LogHelper.WriteCreateNewLog(LogType.signalrError, "signalrSend循环messageList：" + ex.Message);
            }
            MessageDeviceBLL.SendFail_Ids(errorList);
            MessageDeviceBLL.SendSuccess_Ids(successList);
        }
    }
}
